﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;

namespace GianosNET.Common.Classes
{
    public class ConfigSection : IConfigurationSectionHandler
    {
        private Dictionary<string, Hashtable> configs;

        public ConfigSection()
        {
            configs = new Dictionary<string, Hashtable>();
        }

        public Dictionary<string, Hashtable> Configs
        {
            get { return configs; }
        }

        public object Create(object parent, object configContext, XmlNode section)
        {
            DictionarySectionHandler tmp = new DictionarySectionHandler();
            if (section == null)
                return null;

            ConfigSection res = new ConfigSection();

            int i = 0;
            foreach (XmlNode node in section.ChildNodes)
            {
                if (node is XmlElement && node.Name.ToLower() == "config")
                {
                    XmlElement el = node as XmlElement;
                    string name = el.GetAttribute("name");
                    if (string.IsNullOrEmpty(name))
                        name = string.Format("ID##{0}", i);
                    el.Attributes.RemoveAll();

                    object o = tmp.Create(null, null, node);
                    if (o is Hashtable)
                        res.configs.Add(name, o as Hashtable);
                    else
                        throw new Exception("Errore nel file di configurazione");
                }

                i++;
            }

            return res;
        }
    }
}
